//  目标： 实现原生Promise中 执行代码中异常抛错， 只要发生异常就reject掉

//  思路： Promise的异常执行器的异常 executor(this.resolve, this.reject) 和 .then    resolvePromise(promise2, x, resolve, reject);时期的异常。
//          都用try/catch捕获，将错误通过reject进行抛错。

const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECT = 'reject'

class MyPromise6 {
    constructor(executor) {
        try {
            executor(this.resolve, this.reject)
        } catch (error) {
            // 如果有错误，就直接执行 reject
            this.reject(error)
        }
    }

    status = PENDING;

    value = null;

    reason = null;


    onFulfilledCallbacks = [];

    onRejectedCallbacks = [];

    resolve = (value) => {
        if (this.status === PENDING) {
            this.status = FULFILLED;
            this.value = value;

            while (this.onFulfilledCallbacks.length) {
                this.onFulfilledCallbacks.shift()(value)
            }
        }
    }

    reject = (reason) => {
        if (this.status === PENDING) {
            this.status = REJECT;
            this.reason = reason;

            while (this.onRejectedCallbacks.length) {
                this.onRejectedCallbacks.shift()(reason)
            }
        }
    }


    then(onFulfilled, onRejected) {

        const promise2 = new MyPromise6((resolve, reject) => {
            if (this.status === FULFILLED) {
                // 创建一个微任务等待 promise2 完成初始化
                queueMicrotask(() => {

                    try {
                        // 获取成功回调函数的执行结果
                        const x = onFulfilled(this.value);
                        // 传入 resolvePromise 集中处理
                        resolvePromise(promise2, x, resolve, reject);
                    } catch (error) {
                        reject(error)
                    }
                })

            } else if (this.status === REJECT) {

                onRejected(this.reason);
            } else if (this.status === PENDING) {

                this.onFulfilledCallbacks.push(onFulfilled);
                this.onRejectedCallbacks.push(onRejected);

            }
        })
        return promise2;
    }



}

function resolvePromise(promise2, x, resolve, reject) {

    // 如果相等了，说明return的是自己，抛出类型错误并返回
    if (x === promise2) {
        return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    }
    if (x instanceof MyPromise6) {

        x.then(resolve, reject)
    } else {

        resolve(x)
    }
}


const promise = new MyPromise6((resolve, reject) => {
    resolve('success')
    // throw new Error('执行器错误')
 })
 
// 第一个then方法中的错误要在第二个then方法中捕获到
promise.then(value => {
  console.log(1)
  console.log('resolve', value)
  throw new Error('then error')
}, reason => {
  console.log(2)
  console.log(reason.message)
}).then(value => {
  console.log(3)
  console.log(value);
}, reason => {
  console.log(4)
  console.log(reason.message)
})
